﻿using MediatR;
using T.Settlement.Domain.DTO;
using T.Settlement.Domain;
using T.Settlement.Read.API.Application.Command.PaymentCommand;
using T.Settlement.Repository.SettlementInterface;

namespace T.Settlement.Read.API.Application.CommandHandlers.PaymentJandler
{
    public class PaymentApprovalCommandHandler : IRequestHandler<PaymentApprovalCommand, SListDTO<Payment>>
    {
        private readonly IPaymentSRepository _paymentSRepository;
        public PaymentApprovalCommandHandler(IPaymentSRepository paymentSRepository)
        {
            _paymentSRepository = paymentSRepository;
        }
        public async Task<SListDTO<Payment>> Handle(PaymentApprovalCommand request, CancellationToken cancellationToken)
        {
            var list = (await _paymentSRepository.GetAllAsync()).Where(x => !x.IsDeleted&&x.ApprovalStatus>1);
            if (!string.IsNullOrEmpty(request.PaymentTitle))
            {
                list = list.Where(x => x.PaymentTitle.Contains(request.PaymentTitle));
            }
            if (!string.IsNullOrEmpty(request.Approver))
            {
                list = list.Where(x => x.Approver.Contains(request.Approver));
            }
            if (request.PaymentDate != null)
            {
                list = list.Where(x => x.PaymentDate == Convert.ToDateTime(request.PaymentDate).AddDays(1));
            }
            if (request.ApprovalStatus != 0)
            {
                list = list.Where(x => x.ApprovalStatus == request.ApprovalStatus);
            }
            if (!string.IsNullOrEmpty(request.BillingMethod))
            {
                list = list.Where(x => x.BillingMethod == request.BillingMethod);
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                list = list.Where(x => x.CompanyID == request.CompanyID);
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            SListDTO<Payment> page = new SListDTO<Payment>();
            page.TotalCount = list.Count();
            page.TotalPage = (int)Math.Ceiling((double)((page.TotalCount * 1.0) / request.PageSize));
            page.List = list.OrderByDescending(x => x.CreatedDate).Skip((int)((request.PageIndex - 1) * request.PageSize)).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
